package com.flower.wholesale.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flower.wholesale.entity.Manager;
import com.flower.wholesale.enu.RedisKeyEnum;
import com.flower.wholesale.enu.StatausEnum;
import com.flower.wholesale.service.ManagerService;
import com.flower.wholesale.util.CookiesUtil;
import com.flower.wholesale.util.RedisUtil;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 后台管理员账号表 前端控制器
 * </p>
 *
 * @author 姚雁飞
 * @since 2020-01-17
 */
@Controller
@RequestMapping("/manager")
public class ManagerController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(ManagerController.class);

	@Autowired
	private ManagerService managerService;
	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 
	 * @author: 姚雁飞
	 * @desc: 后台管理员登录
	 * @date: 2020年4月7日 下午4:33:57
	 * @param request
	 * @param response
	 * @param name     登录名
	 * @param password 密码
	 * @param code     验证码
	 * @throws IOException
	 */
	@PostMapping("/login")
	public void login(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "name", required = true) String name,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "code", required = true) String code) throws IOException {
		JSONObject result = new JSONObject();
		if (StringUtils.isEmpty(name)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "用户名不能为空");
			responseJson(response, result);
			return;
		}
		if (StringUtils.isEmpty(password)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "密码不能为空");
			responseJson(response, result);
			return;
		}
		if (StringUtils.isEmpty(code)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "验证码不能为空");
			responseJson(response, result);
			return;
		}
		Cookie cookie = CookiesUtil.getCookieByName(request, "verificationCode");
		String uuid = cookie.getValue();
		String sessionCode = redisUtil.get(RedisKeyEnum.VERIFICATION_CODE.getKey() + uuid).toString();
		if (sessionCode == null || !sessionCode.equalsIgnoreCase(code)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "验证码输入有误");
			responseJson(response, result);
			return;
		}
		
		result = managerService.login(name, password, sessionCode);
		if (StatausEnum.SUCCESS.getCode() == result.getInteger("code")) {//登录成功
			Manager manager = (Manager) result.get("data");
			result.remove("data");
			String jsonString = JSON.toJSON(manager).toString();
			String managerInfo = UUID.randomUUID().toString();
			redisUtil.set(RedisKeyEnum.MANAGER_INFO.getKey()+managerInfo, jsonString, 60*30);
			//response.addHeader("managerInfo", managerInfo);
			CookiesUtil.setCookie(response, "managerInfo", managerInfo, 60*30);
		}
		
		responseJson(response, result);
		return;
	}

	/**
	 * 
	 * @author: 姚雁飞
	 * @desc: 添加管理员
	 * @date: 2020年4月7日 下午4:34:38
	 * @param request
	 * @param response
	 * @param loginName  登录名
	 * @param password   密码
	 * @param repassword 再次输入密码
	 * @throws IOException
	 */
	@PostMapping("/addManager")
	public void addManager(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "loginName", required = true) String loginName,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "repassword", required = true) String repassword,
			@RequestParam(value = "status", required = true,defaultValue = "1") Integer status) throws IOException {
		JSONObject result = new JSONObject();
		if (StringUtils.isEmpty(loginName)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "登录名不能为空！");
			responseJson(response, result);
			return;
		}
		if (StringUtils.isEmpty(password) || StringUtils.isEmpty(repassword)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "密码不能为空！");
			responseJson(response, result);
			return;
		}
		if (!StringUtils.equals(password, repassword)) {// 判断两次输入的密码是否一致
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "两次密码不一致");
			responseJson(response, result);
			return;
		}
		QueryWrapper<Manager> queryWrapper = new QueryWrapper<Manager>();
		queryWrapper.eq("login_name", loginName);
		Manager manager = managerService.getOne(queryWrapper);
		if (manager != null) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "已经存在该用户，请换用户名重新录入！");
			responseJson(response, result);
			return;
		}
		Manager entity = new Manager();
		entity.setLoginName(loginName);
		entity.setPassword(password);
		entity.setStatus(status);
		Date date = new Date();
		entity.setCreateTime(date);
		entity.setUpdateTime(date);
		boolean falg = managerService.save(entity);
		if (falg) {
			result.put("code", StatausEnum.SUCCESS.getCode());
			result.put("msg", "添加管理员成功");
			responseJson(response, result);
			return;
		} else {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "添加管理员失败");
			responseJson(response, result);
			return;
		}
	}

	/**
	 * 
	 * @author: 姚雁飞
	 * @desc: 管理员分页查询
	 * @date: 2020年4月17日 下午6:06:58
	 * @param request
	 * @param response
	 * @param loginName 登录名
	 * @param offset 页码
	 * @param limit  每页显示的条数
	 * @throws IOException
	 */
	@PostMapping("/getPager")
	public void getPager(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "loginName", required = false, defaultValue = "") String loginName,
			@RequestParam(value = "status", required = false,defaultValue = "") String status,
			@RequestParam(value = "pageNo", required = true) int pageNo,
			@RequestParam(value = "pageSize", required = true, defaultValue = "10") int pageSize
			) throws IOException {
		JSONObject result = new JSONObject();
		result.put("code", StatausEnum.SUCCESS.getCode());
		result.put("msg",  StatausEnum.SUCCESS.getMsg());
		QueryWrapper<Manager> queryWrapper = new QueryWrapper<Manager>();
		if(StringUtils.isNotEmpty(loginName)) {
			queryWrapper.like("login_name", loginName);
		}
		if(StringUtils.isNotEmpty(status)) {
			queryWrapper.eq("status", status);
		}
		IPage<Manager> page = new Page<Manager>(1, 10);
		page.setCurrent(pageNo);
		page.setSize(pageSize);
		page = managerService.page(page, queryWrapper);
		result.put("total", page.getTotal());
		result.put("pageNumber", pageNo);
		result.put("rows",JSON.toJSON(page.getRecords()));
		//result.put("data", page);
		logger.info("查询结果======"+result);
		responseJson(response, result);
	}
	/**
	 * 
	 * @author: 姚雁飞
	 * @desc: 根据id查询用户信息
	 * @date: 2020年4月20日 下午2:16:51
	 * @param request
	 * @param response
	 * @param id 管理员ID
	 * @throws IOException 
	 */
	@PostMapping("/getManagerById")
	public void getManagerById(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true, defaultValue = "") String id) throws IOException {
		JSONObject result = new JSONObject();
		result.put("code", StatausEnum.SUCCESS.getCode());
		result.put("msg",  StatausEnum.SUCCESS.getMsg());
		if(StringUtils.isEmpty(id)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg",  "id不能为空！");
			responseJson(response, result);
			return;
		}
		Manager manager = managerService.getById(id);
		result.put("data", manager);
		responseJson(response, result);
	}
	
	/**
	 * 
	 * @author: 姚雁飞
	 * @desc: 更新管理员信息
	 * @date: 2020年4月20日 下午2:23:29
	 * @param request
	 * @param response
	 * @param id 管理员id
	 * @param password 管理员密码
	 * @param status 管理员状态
	 * @throws IOException 
	 */
	@PostMapping("/updateManagerById")
	public void updateManagerById(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true, defaultValue = "") String id,
			@RequestParam(value = "password", required = false, defaultValue = "") String password,
			@RequestParam(value = "status", required = false, defaultValue = "") String status) throws IOException {
		JSONObject result = new JSONObject();
		result.put("code", StatausEnum.SUCCESS.getCode());
		result.put("msg", StatausEnum.SUCCESS.getMsg());
		if (StringUtils.isEmpty(id)) {
			result.put("code", StatausEnum.Error.getCode());
			result.put("msg", "id不能为空！");
			responseJson(response, result);
			return;
		}
		Manager manager = managerService.getById(id);
		if (StringUtils.isNotEmpty(password)) {
			manager.setPassword(password);
		}
		if (StringUtils.isNotEmpty(status)) {
			manager.setStatus(Integer.valueOf(status));
		}
		managerService.saveOrUpdate(manager);
		responseJson(response, result);
	}
	
	
}
